var $registTableList = $('#registTableList');  //
//防止表头与表格不对齐
$(window).resize(function () {
    $registTableList.bootstrapTable('resetView');
});
$(function () {
    //表格
    registTableListInit();
    $('#selectReview').selectpicker();
    // 初始化下拉菜单
    $('#deduction').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });

    $('#signState').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });
    $('#sign').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });
    $('.date-input').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    })
    selectCompanyList()
})
//参数
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //普通搜索条件
    // params.courseArrangeId = window.location.search.split('=')[1]
    params.courseArrangeId = $('#courseArrangeId').val();

    params.courseName = params.courseName
    params.coursePlace = params.coursePlace
    params.searchType = $('#selectReview').val();
    params.searchName = $('#courseName').val();
    params.companyId  = $('#companyId').val();
    params.isConsume = $('#deduction').val();
    params.registStatus = $('#signState').val();
    params.isSign = $('#sign').val();
    params.startTm  = $('#createTmStart').val();
    params.endTm  = $('#createTmEnd').val();
    // params.contractNumber = $.trim($('#contractNumberMin').val());//合同编号
    return params;
}
//表格序号
function indexFormat(value, row, index) {
    return index + 1;
}
//表格操作
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" id="detail">取消</button>';
    html += '<button class="btn btn-default" id="reviewed">扣次</button>';
    html += '<button class="btn btn-default" id="sign">签到</button>';
    return html;
}

function registStatusTitle(value, row, index) {
    let tooltipstring;
    if(value=='审核未通过'){
        //title=' + value + '(' + row.cancelType + ')' + '
        tooltipstring='<span style="color: #4d5259" href="#" data-html="false" data-toggle="tooltip" data-placement="left" title='  + row.cancelType + '>' + value + '</span>'
    }else{
        tooltipstring='<span style="color: #4d5259" href="#"  >' + value + '</span>'
    }
    // html += '<button class="btn btn-default" id="detail">取消</button>';
    // html += '<button class="btn btn-default" id="reviewed">扣次</button>';
    // if()
    // return html;
    return [
        '<div id="updateReadState">',
        tooltipstring,
        '</div>',
    ].join('');
}





function registTableListInit(){
    //先销毁表格
    $registTableList.bootstrapTable('destroy');
    $registTableList.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/courseArrange/selectAuditRegistList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'contractId',
        idField: 'contractId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        //cell没有值时显示
        undefinedText: '-',

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'contractId', visible: false},
            {title: '课程ID', field: 'courseId', visible: false},
            {checkbox: true, visible: true},
            // {title: '序号', field: 'index', align: 'center', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '参课人' ,field: 'applyName',align: 'left', valign: 'middle',class: 'ellipsis'},
            {title: '联系方式', field: 'contactWay', align:'left',  valign: 'middle'},
            {title: '扣次', field: 'isConsume', align:'left',  valign: 'middle',formatter:function (value, row, index) {
                if(value == 0){
                    return '未扣次'
                }else{
                    return '已扣次'
                }
            }},
            {title: '报名状态', field: 'registStatus',sortable: true,align:'left', valign:'middle', formatter:function (value, row, index) {
                if(value == 0){
                    return '报名中'
                }else  if(value == 1){
                    return '报名成功'
                }else{
                    return '已取消'
                }
            }},
            {title: '报名时间', field: 'createTm', align:'left',  valign: 'middle',formatter:function(value,row,index){
                return dateFormat(value)
            }},
            // {title: '报名编码', field: 'courseRegistrationId', align:'left',  valign: 'middle'},
            {title: '所属分公司', field: 'companyName',align:'left', valign:'middle'},
            // {title: '所属客户', field: 'customerName',align:'left', valign:'middle'},
            {title: '所有人', field: 'userName',align:'left', valign:'middle'},
            {title: '取消人', field: 'cancelPersonName',align:'left', valign:'middle'},
            {title: '取消时间', field: 'cancelTm',align:'left', valign:'middle'},
            {title: '是否签到', field: 'isSign',align:'left', valign:'middle',formatter:function (value, row, index) {
                if(value == 0){
                    return '未签到'
                }else{
                    return '已签到'
                }
            }},
            {title: '操作',field: 'operateFlag',width: '200',align: 'right',events:operateEvents, formatter: genderOpt},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                if(result.data.length>0){
                    $("#courseIdData").val(result.data[0].courseId)
                }

            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },

        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

//显示
$('#myModalCancellation').modal('show')

//隐藏
$('#myModalCancellation').modal('hide')
//监听事件
window.operateEvents = {
    //取消
    'click #detail': function (e, value, row, index) {
        //报名结束时间截止的不可取消
        var enterEndTm = $("#enterEndTm").val();
        var nowtimeYMDHM = new Date().FormatFMT("yyyy-MM-dd hh:mm");
        if (enterEndTm < nowtimeYMDHM) {
            $.alert("报名已结束不可取消!");
            return;
        }

        //已取消的不可再次取消
        if (row.registStatus == 2){
            $.alert("不可重复取消!");
            return;
        }

        $("#registIdName").val(row.courseRegistrationId);
        $("#isConsumeHidden").val(row.isConsume);
        $('#myModalCancellation').modal('show');
    },

    //扣次
    'click #reviewed': function (e, value, row, index) {

        let courseConsumeData={
            "courseId": row.courseId,
            "registList":[row.courseRegistrationId]
        }

        courseArrangeFun(courseConsumeData)
    }
};
// //一键扣次
// $("#btn-search-simple").on('click',function () {
//     if($registTableList.bootstrapTable('getSelections').length<=0){
//         $.alert("请勾选扣次")
//     }else{
//         let arrayRegistList=[],tableSelected=$registTableList.bootstrapTable('getSelections')
//         for(let i=0,len=tableSelected.length;i<len;i++){
//             arrayRegistList.push(tableSelected[i].courseRegistrationId)
//         }
//         let courseConsumeData={
//             "courseId": $("#courseIdData").val(),
//             "registList":arrayRegistList
//         }
//         courseArrangeFun(courseConsumeData)
//
//     }
//
// })

$("#reasonCause").on('click',function () {
    if($("#followContent").val().length==0){
        $(".fault-tolerant").show()
    }else{
        var auditCancelData={
            "registId": $("#registIdName").val(),
            "cancelReason": $("#followContent").val(),
            "isConsume": $("#isConsumeHidden").val()
        }
        $.ajax({
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            url: '/courseArrange/auditCancel',
            data:JSON.stringify(auditCancelData),
            success: (function (data) {
                if(data.code == '000000'){
                    $.alert('操作成功!')
                    $('#myModalCancellation').modal('hide')
                    // $registTableList.bootstrapTable('refresh');
                    $registTableList.bootstrapTable('refreshOptions', {pageNumber: 1});
                }else{
                    $.alert('操作失败!')
                }
            }),
            error: (function (res) {
                alert("请求失败");
            })
        })
    }
})
$("#followContent").on('keyup',function () {
    $(".fault-tolerant").hide()
})

//扣次接口
function courseArrangeFun(courseConsumeData) {
    $.ajax({
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        url: '/courseArrange/courseConsume',
        data:JSON.stringify(courseConsumeData),
        success: (function (data) {
            if(data.code == '000000'){
                // $registTableList.bootstrapTable('refresh');
                $.alert('操作成功!')
                $registTableList.bootstrapTable('refreshOptions', {pageNumber: 1});
            }else{
                $.alert(data.data)
            }
        })
    })
}

/**
 * 时间转换
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function dateFormat(value, row, index) {
    if (value != null) {
        var date = new Date(value);
        var month = date.getMonth()+1;
        var tian = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (tian >= 1 && tian <= 9) {
            tian = "0" + tian;
        }

        return date.getFullYear() + '-' + month + '-' + tian;
    }
}


/**
 * 查询所有的公司
 */
function selectCompanyList() {
    $.ajax({
        type: 'get',
        dataType: "json",
        url: '/company/getCompanyList',
        cache: false,
        async: false,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '<option value="">全部</option>';
                $.each(data.data, function (n, value) {
                    html += "<option value=" + value.companyId + ">" + value.companyName + "</option>";
                });
            }
            $("#companyId").html(html);
            $('#companyId').selectpicker({
                noneSelectedText: '请选择',
                sanitize: true,
                size: 10
            });
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

function reset() {
    $('#filterContent select').val('').selectpicker('refresh');
    $('.date-input').val('');
}